<?php

namespace app\api\controller;

use app\api\model\Comment as CommentModel;
use app\api\model\Order as OrderModel;
use app\common\controller\Api;

/**
 * 评论接口
 */
class Comment extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['index'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    public function index()
    {
        if ($this->request->isGet()) {
            //获取参数
            $data = $this->request->param();
            //助手函数实例化验证器
            $validate = validate('Comment');
            if (!$validate->scene('index')->check($data)) {
                $this->error($validate->getError());
            }
            // 美食id
            $deal_id = $data['deal_id'];
            // 页数
            $pageNum = $data['pageNum'] ?? 1;
            // 每页数量
            $pageSize = $data['pageSize'] ?? 10;
            //    实例化订单模型
            $order = new OrderModel();
            // 根据美食id查询对应订单
            $order_ids = $order->where('food_id', $deal_id)->column('id');
            // dump($order_ids);
            $comments = CommentModel::all(function ($query) use ($order_ids, $pageNum, $pageSize) {
                $query->where('order_id', 'in', $order_ids)->page($pageNum, $pageSize);
            });
            if (empty($comments)) {
                $this->error('暂无评论');
            }
            // dump($list);
            // 返回数组
            $result = [];
            foreach ($comments as $key => $comment) {
                $result[] = [
                    'user_id' => $comment->user->id,
                    'user_photo' => $comment->user->avatar,
                    'comment' => $comment->content,
                    'comment_imgs' => $comment->comment_imgs ? json_decode($comment->comment_imgs) : $comment->comment_imgs,
                ];
            }
            $this->success('查询成功', [
                'rows' => $result
            ]);
        }
    }

    public function add()
    {
        if ($this->request->isPost()) {
            //获取参数
            $data = $this->request->param();
            // dump($data);
            // exit;
            //助手函数实例化验证器
            $validate = validate('Comment');
            if (!$validate->scene('add')->check($data)) {
                $this->error($validate->getError());
            }

            //验证订单归属
            $order = OrderModel::get(['id' => $data['orderID']]);
            if (!$order) {
                $this->error('订单不属于你');
            }

            // 处理评论图片
            $commentImgs = [];
            if (!empty($data['commentImgs'])) {
                $commentImgs = is_string($data['commentImgs']) ? json_decode($data['commentImgs'], true) : $data['commentImgs'];
            }

            // 保存评论（新增：存储星级 rate）
            $comment = new CommentModel();
            $comment->save([
                'user_id'    => $this->auth->__get('id'),
                'order_id'   => $data['orderID'],
                'user_avatar' => $this->auth->__get('avatar'),
                'content'    => $data['comment'],
                'comment_imgs' => json_encode($commentImgs),
                'rate'       => $data['rate'] // 存储星级
            ]);

            // 更新订单的 is_commented 字段（原有逻辑）
            $order->is_commented = 1;
            $order->save();

            $this->success('评论成功');
        }
    }
}
